package com.dbpms.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

public class MybatisPlusConfig {

    // mybatis和spring整合
    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSource dataSource,MybatisPlusInterceptor mybatisPlusInterceptor) throws IOException {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        // 设置数据源
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.dbpms.pojo");
        // 设置mapper.xml文件的路径
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml");
        factoryBean.setMapperLocations(resources);

        factoryBean.setPlugins(mybatisPlusInterceptor);

        return factoryBean;
    }
    // 用于自动扫描指定包路径下的 Java 接口，将其注册为 MyBatis 的 Mapper 接口，从而使这些接口能够被 MyBatis 所管理和调用。省去写@Mapper 注解
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.dbpms.mapper");
        return msc;
    }
    // 分页的插件配置
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        // 1.初始化核心插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 2.添加分页插件
        PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); // 配置数据库类型
        pageInterceptor.setMaxLimit(1000L); // 设置分页数量上限
        // 优化Join分页语句，默认true
        pageInterceptor.setOptimizeJoin(true);
        // 是否对超过最大分页时做溢出处理
        pageInterceptor.setOverflow(true);
        interceptor.addInnerInterceptor(pageInterceptor);
        return interceptor;
    }

}